package com.last.service.impl;

import com.api.city.CityApi;
import com.last.bean.SearchBean;
import com.last.entity.Result;
import com.last.entity.RoomInfo;
import com.last.service.IHousingDetailService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class HousingDetailService implements IHousingDetailService {
    @Autowired
    private CityApi houseDetailApi;
    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Override // 获取房源详情+房型列表
    public Result getHouseDetailInfo(Integer homeId) {
        SearchBean content = null;
        try {
            TermQueryBuilder termQuery = QueryBuilders.termQuery("homeId", homeId);
            NativeSearchQuery build = new NativeSearchQueryBuilder().withQuery(termQuery).build();
            SearchHits<SearchBean> searchHits = restTemplate.search(build, SearchBean.class);
            SearchHit<SearchBean> searchHit = searchHits.getSearchHit(0);
            content = searchHit.getContent();
            return new Result(true, "查询成功", content);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败,请输入正确的房源ID", null);
        }
    }

    @Override
    public Result roomInfoList(Integer homeId) {
        List<RoomInfo> housingDetail = houseDetailApi.getHousingDetail(homeId);
        if(housingDetail.size() != 0){
            return new Result(true, "查询列表成功", housingDetail);
        }else {
            return new Result(false, "查询列表失败", null);
        }
    }


}
